<?php
include("functions.php");  


//controllo sessione per pagine riservate 
function reserved_page()
{		
		if (!isset($_SESSION['id']) || !isset($_SESSION['mail']) || !isset($_SESSION['user']) || !isset($_SESSION['id_fb']))
		//accesso negato
			header("Location: http://www.giorgioprovenzale.it/sites/ragusainfoto/index.php?code_err=6");
}

//controllo sessione per pagine riservate agli amministratori 
function admin_page()
{		
		if (!$_SESSION['admin'])
		//accesso negato
			header("Location: http://www.giorgioprovenzale.it/sites/ragusainfoto/index.php?code_err=7");
}

//pagine solo per utenti non loggati
function only_no_logged()
{		
		if (isset($_SESSION['id']))
		//accesso negato
			header("Location: http://www.giorgioprovenzale.it/sites/ragusainfoto/index.php?code_err=8");
}

//recupera sessione da cookie
function get_session($id_session)
{
	include("database.php"); 
	
	mysql_select_db($database_database, $database);
	$query = "SELECT name, surname, user, mail, admin, id, id_fb FROM sessions WHERE id_session='".$id_session."'";
	$result = mysql_query($query, $database) or die(mysql_error());
	$result_rows = mysql_num_rows($result);
	$result_array = mysql_fetch_array($result);
	
	$user = $result_array['user'];
	$name = $result_array['name'];
	$surname = $result_array['surname'];
	$admin = $result_array['admin'];
	$mail = $result_array['mail'];
	$id = $result_array['id'];
	$id_fb = $result_array['id_fb'];
	
	if($result_rows)//se c'è la sessione salvata
	{
		$query = "DELETE FROM sessions WHERE id_session='".$id_session."'";
		$result = mysql_query($query, $database) or die(mysql_error());
	
		create_session($user, $name, $surname, $admin, $mail, $id, $id_fb);
	}
	
}

//crea sessione
function create_session($username, $name, $surname, $admin, $mail, $id, $id_fb)
{
	ob_start();
	session_start();
	
	$_SESSION['user'] = $username;
	$_SESSION['mail'] = $mail;
	$_SESSION['name'] = $name;
	$_SESSION['surname'] = $surname;
	$_SESSION['admin'] = $admin; 
	$_SESSION['id'] = $id;
	$_SESSION['id_fb'] = $id_fb;
	
	include("database.php"); 
	
	$id_session = get_session_code();
	mysql_select_db($database_database, $database);
	$sql = "INSERT INTO sessions SET name='".$name."', surname='".$surname."', user='".$username."', mail='".$mail."',admin='".$admin."', id='".$id."', id_fb='".$id_fb."', id_session='".$id_session."'";
	$result = mysql_query($sql, $database) or die(mysql_error());
	
	setcookie("ragusainfoto", $id_session, time()+7200);
}

function logout()
{
	$type = (int)$type;
	
	include("database.php");
	
	session_start();
	
	$id = (int)$_SESSION['id'];
	
	mysql_select_db($database_Database, $Database);
	$query = "DELETE FROM sessions WHERE id='".$id."'";
	$result = mysql_query($query, $database) or die(mysql_error());

	$_SESSION['user'] = null;
	$_SESSION['mail'] = null;
	$_SESSION['name'] = null;
	$_SESSION['surname'] = null;
	$_SESSION['admin'] = null; 
	$_SESSION['id'] = null;
	$_SESSION['id_fb'] = null;
	unset($_SESSION['user']);
	unset($_SESSION['mail']);
	unset($_SESSION['name']);
	unset($_SESSION['surname']);
	unset($_SESSION['admin']);
	unset($_SESSION['id']);
	unset($_SESSION['id_fb']);
	
	session_destroy();
	session_unset();
	
	setcookie("ragusainfoto", 0, time()-7200);
	
	return;
}

//controllo dei dati di login
function check_login($mail, $pass)
{ 	
	include("database.php"); 
	mysql_select_db($database_database, $database);
	$query = "SELECT name, surname, user, admin, verificated, id, id_fb FROM users WHERE mail='".$mail."' AND pass='".$pass."'";
	$result = mysql_query($query, $database) or die(mysql_error());
	$result_rows = mysql_num_rows($result);
	$result_array = mysql_fetch_array($result);
	
	if($result_rows)
	{
		//utente esistente
		if($result_array['verificated'])
		{
			//utente verificato
			create_session($result_array['user'], $result_array['name'], $result_array['surname'], $result_array['admin'], $mail, $result_array['id'], $result_array['id_fb']);    
			header("Location: index.php");
		}
		//utente non verificato
		else
			header("Location: index.php?code_err=3");
	}
	else
		//dati login errati
		header("Location: index.php?code_err=2");
	
}

//recupero id dall'id Facebook
function get_id($id_fb)
{
	include("database.php"); 
	mysql_select_db($database_database, $database);
	$query = "SELECT id FROM users WHERE id_fb='".$id_fb."'";
	$result = mysql_query($query, $database) or die(mysql_error());
	$result_rows = mysql_num_rows($result);
	$result_array = mysql_fetch_array($result);
	
	return $result_array['id']; 

}

//controlla che l'utente loggato con facebook è anche registrato
function check_login_fb($username, $name, $surname, $mail, $id_fb, $place)
{ 	
	include("database.php"); 
	mysql_select_db($database_database, $database);
	$query = "SELECT name, surname, user, admin, verificated, id, mail FROM users WHERE id_fb='".$id_fb."'";//controllo sull'id di facebook
	$result = mysql_query($query, $database) or die(mysql_error());
	$result_rows = mysql_num_rows($result);
	$result_array = mysql_fetch_array($result);
	
	$id = $result_array['id'];
	$admin = $result_array['admin'];
	
	if($result_rows)
	{
		//utente fb è registrato
		if($result_array['verificated'])
		{
			//utente fb è verificato
			//controllo che i valori di facebook sono ancora uguali a quelli presenti nel db, in caso contrario sovrascrivo
			if( (strcmp($name, $result_array['name']) != 0) || (strcmp($surname, $result_array['surname']) != 0) || (strcmp($username, $result_array['user']) != 0) || (strcmp($mail, $result_array['mail']) != 0) )
			{
				$sql="UPDATE users SET name = '".$name."', surname = '".$surname."', user = '".$username."', mail = '".$mail."' WHERE id_fb='".$id_fb."'";
				$result = mysql_query($sql, $database) or die(mysql_error());
			}

			//utente fb è registrato e il account fb è collegato
			create_session($username, $name, $surname, $admin, $mail, $id, $id_fb);  
			header("Location: index.php");
		}
		//utente fb non è verificato
		else
			header("Location: index.php?code_err=3");
	}
	else
		//utente loggato con fb ma non è registrato oppure è un utente gia registrato che collega l'account fb
		req_user_fb($username, $name, $surname, $mail, $id_fb, $place);
		header("Location: index.php");
	
}

//generatore di serie alfanumerica casuale
function get_random_code()
{
	$length = 10;
	$start = rand(0, 31-$length);
	$key = substr(md5(rand()), $start, $length);
	return $key;	
}

function get_session_code()
{
	$length = 28;
	$start = rand(0, 31-$length);
	$key = substr(md5(rand()), $start, $length);
	return $key;	
}

//invio mail per verificare indirizzo mail
function mail_req($name, $surname, $mail, $id, $code)
{
	$message = "Clicca qui http://www.giorgioprovenzale.it/sites/ragusainfoto/registration/confirmation.php?id=".$id."&code=".$code.".";

	$headers= "From:ragusainfoto@giorgioprovenzale.it\n";
	$headers .= "Reply-To:ragusainfoto@giorgioprovenzale.it\n";
	$headers .= "X-Mailer: PHP/".phpversion()."\n";

	mail($mail,"Registrazione Ragusainfoto",$message,$headers);
}
//registra utente
function req_user_fb($username, $name, $surname, $mail, $id_fb, $place)
{
	include("database.php");
	//controllo se ci sono users con la stessa mail 
	mysql_select_db($database_database, $database);
	$query = "SELECT name, surname, user, admin, verificated, id, mail FROM users WHERE mail='".$mail."'";
	$result = mysql_query($query, $database) or die(mysql_error());
	$result_rows = mysql_num_rows($result);
	$result_array = mysql_fetch_array($result);
	
	//ci sono utenti con la stessa mail
	if($result_rows)
	{
	//aggiorno dati utente con i dati facebook
		$code = get_random_code();
		$sql = "UPDATE users SET name='".$name."', surname='".$surname."', user='".$username."', pass='', verificated='1', place='".$place."', code='".$code."', id_fb='".$id_fb."' WHERE mail='".$mail."'";
		$result = mysql_query($sql, $database) or die(mysql_error()); 
		
		logout();//logout prima di creare una nuova sessione con i nuovi dati
	}
	else //utente completamente nuovo
	{
		$sql = "INSERT INTO users SET name='".$name."', surname='".$surname."', user='".$username."', mail='".$mail."',admin='0', verificated='1', place='".$place."', code='".$code."', id_fb='".$id_fb."'";
		$result = mysql_query($sql, $database) or die(mysql_error());
	}
	
	//recupero id
	$query = "SELECT id FROM users WHERE id_fb='".$id_fb."'";
	$result = mysql_query($query, $database) or die(mysql_error());
	
	$admin = 0;
	
	create_session($username, $name, $surname, $admin, $mail, $result_array['id'], $id_fb);
	
	return;
}

//registra utente
function req_user($name, $surname, $pass, $mail, $place)
{
	include("database.php"); 
	
	$name = ucfirst(strtolower($name));
	$name = strip_tags($name);
	$surname = ucfirst(strtolower($surname));
	$surname = strip_tags($surname);
	$place = ucfirst(strtolower($place));
	$place = strip_tags($place);
	$pass = strip_tags($pass);
	$mail = strtolower($mail);
	$mail = strip_tags($mail);
	$code = get_random_code();
	$user = $name." ".$surname;
	
	mysql_select_db($database_database, $database);
	$sql = "INSERT INTO users SET name='".$name."', surname='".$surname."', user='".$user."', mail='".$mail."', pass='".$pass."',  code='".$code."', place='".$place."'";
	$result = mysql_query($sql, $database) or die(mysql_error());
	
	$sql="SELECT id FROM users WHERE mail='".$mail."'";
	$result = mysql_query($sql, $database) or die(mysql_error());
	$result_array = mysql_fetch_array($result);
	
	//invio mail di verifica
	mail_req($name, $surname, $mail, $result_array['id'], $code);
	
	return;
}

//verifica utente
function verify_user($id, $code)
{
	include("database.php"); 
	mysql_select_db($database_database, $database);
	$sql="SELECT name, surname, user, mail, admin, code, verificated, id_fb FROM users WHERE id='".$id."'";
	$result = mysql_query($sql, $database) or die(mysql_error());
	$result_rows = mysql_num_rows($result);
	$result_array = mysql_fetch_array($result);
	if(!$result_array['verificated'])//utente non ancora validato
	{
		if(strcmp($code, $result_array['code']) == 0)
		{
			$code = get_random_code();
			//verifica utente e cambio il code
			$sql="UPDATE users SET verificated = '1', code = '".$code."' WHERE id='".$id."'";
			$result = mysql_query($sql, $database) or die(mysql_error());
			
			create_session($result_array['user'], $result_array['name'], $result_array['surname'], $result_array['admin'], $result_array['mail'], $id, $result_array['id_fb']);
			
			return 1; //ok utente verificato
		}
		else
			return -1; //errore di code o di id
	}	
	else
		return 0; //già verificato
}

//reset password
function reset_password($mail)
{
	include("database.php"); 
	$new_pass = get_random_code();
	mysql_select_db($database_database, $database);
	$sql="UPDATE users SET pass='".$new_pass."' WHERE mail='".$mail."'";
	$result = mysql_query($sql, $database) or die(mysql_error());
	
	$message = "La password è stata resettata. La nuova password è ".$new_pass.". Dopo il login la password può essere modificata dalla pagina del profilo personale.";

	$headers= "From:ragusainfoto@giorgioprovenzale.it\n";
	$headers .= "Reply-To:ragusainfoto@giorgioprovenzale.it\n";
	$headers .= "X-Mailer: PHP/".phpversion()."\n";

	mail($mail,"Reset Password",$message,$headers);
	
	header("Location: ../index.php?code_err=9");
}

?>